package com.conversationboard.formatter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Class to transform a piece of plain text into one that's marked up with HTML
 * <p>
 * tags to denote paragraphs.
 * 
 * @author Keith Watson
 * 
 */

public class ParagraphFormatter {

	private static final Pattern paragraphBreaks = Pattern.compile("(\\n|\\u000a|\\u000d){4,}", (Pattern.CASE_INSENSITIVE | Pattern.DOTALL));
	private static final Pattern newLines = Pattern.compile("\\n{1}", (Pattern.CASE_INSENSITIVE | Pattern.DOTALL));


	public String format(String input) {

		input = input.trim();

		/* First look for paragraph breaks and mark them up as such */

		Matcher matcher = paragraphBreaks.matcher(input);
		String output = matcher.replaceAll("</p><p>");

		output = "<p>" + output + "</p>";

		/* Now look for only single newlines and insert BR tags */

		Matcher newLineMatcher = newLines.matcher(output);
		output = newLineMatcher.replaceAll("<br />");

		/* Remove all actual newline characters from the output */
		output = output.replaceAll("[\\r\\f\\n]", "");

		return output;

	}

}
